package utils

import "fmt"
import "crypto/md5"
import "math/rand"
import "time"
import "strconv"
import (
	"strings"
	"encoding/json"
	"github.com/axgle/mahonia"
)

func GetTimes() string {
	timestamp := time.Now().Unix()
	stringtimes := strconv.FormatInt(timestamp, 10)
	return stringtimes
}
func GetTimesInt() int64 {
	timestamp := time.Now().Unix()
	return timestamp
}

func GetNowTime() string{
	now := time.Now().Format("2006-01-02 15:04:05")
	return now
}

func GoAbs(input int64) (ret int64) {
	ret = (input ^ input>>31) - input>>31
	return ret
}

//将字符串加密成 md5
func String2md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	return fmt.Sprintf("%x", has) //将[]byte转成16进制
}

//RandomString 在数字、大写字母、小写字母范围内生成num位的随机字符串
func RandomString(length int) string {
	// 48 ~ 57 数字
	// 65 ~ 90 A ~ Z
	// 97 ~ 122 a ~ z
	// 一共62个字符，在0~61进行随机，小于10时，在数字范围随机，
	// 小于36在大写范围内随机，其他在小写范围随机
	rand.Seed(time.Now().UnixNano())
	result := make([]string, 0, length)
	for i := 0; i < length; i++ {
		t := rand.Intn(62)
		if t < 10 {
			result = append(result, strconv.Itoa(rand.Intn(10)))
		} else if t < 36 {
			result = append(result, string(rand.Intn(26)+65))
		} else {
			result = append(result, string(rand.Intn(26)+97))
		}
	}
	return strings.Join(result, "")
}

/*
类似php中的in_array
 */
func StringInArray(needle string, haystack []string) bool{
	result := false
	for _, item := range haystack{
		if(needle == item){
			result = true
			break
		}
	}
	return result
}

func JsonEncode(object interface{}) string {
	jsonencode,_:=json.Marshal(object)
	jsonstr := string(jsonencode[:])
	return jsonstr
}
func JsonDecode(string string) interface{}{
	var byteJson []byte = []byte(string)
	var result interface{}
	json.Unmarshal(byteJson, &result)
	return result
}

func Str2Byte(string string) []byte{
	var data []byte = []byte(string)
	return data
}
func Byte2Str(byte []byte) string{
	string := string(byte[:])
	return string
}

func ConvertToString(src string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	result := string(cdata)
	return result
}

//字符串截取
func Substr(str string, start int, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0

	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}
	return string(rs[start:end])
}